<?php 
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends CommonController{
	//分类列表
	public function index(){
		$cate = M('cate')->order("sort ASC")->select();
		$cate = \Util\Category::unlimitedForLevel($cate);
		$this->cate =$cate;
		$this->display();
	} 
	//添加分类
	public function addCate(){
		$this->pid = I('pid','0','intval');
		$this->display();
	}
	//添加分类处理表单
	public function addCateHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		$name=I('name');
		if(!empty($name)){ //如果分类名不为空
			if(M('cate')->add(I())){
				$this->success("添加成功");
			}else{
				$this->success("添加失败");
			}		
		}else{
			$this->error("分类名不能为空");
		}

	}	
	//分类排序
	public function sortCate(){
		$db = M('cate');
		foreach (I() as $id => $sort) {
			$db-> where(array("id"=>$id))->setField('sort',$sort);
		}
		$this->success("更新成功");
	}
	//删除分类
	public function delCateHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		$cate = M('cate')->order("sort ASC")->select();
		$childs = \Util\Category::getChildsId($cate,I('id')); //当前分类的子分类

		if(empty($childs)){ //如果子分类为空
			if(M('cate')->where( array("id"=>I('id')) )-> delete()){
				$this->success("删除成功");
			}else{ 
				$this->error("未知原因,删除失败!");
			}		
		}else{//如果不子分类为空
			$this->error("请先删除子分类!");
		}
	}
	//修改分类信息
	public function changeCate(){
		$this->pid = I('pid','','intval');
		$this->id = I('id','','intval');
		$this->name = I('name');
		$this->display();
	}
	//更新分类信息处理表单
	public function changeCateHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		$db = M('cate');
		$id = I('id','','intval');
		$data['name'] = I('name');
		$data['pid'] = I('pid','','intval');
		if($db->where(array("id"=>$id))->save($data)){
			$this->success("字段更细成功",__CONTROLLER__."/index");
		}else{
			$this->error("字段更新失败",__CONTROLLER__."/index");
		}
	}
	//TODO


}